<?php
class IndexAction extends CommonAction {

    public function index(){
        $user = D('User');
        $current = $user->field(array('id', 'name', 'email', 'reg_time', 'last_time', 'last_ip', 'account', 'score'))
             ->where("name='{$_COOKIE['user']}'")
             ->find();
        //获取发布信息总条数
        $info = M('Info');
        $infoCount = $info->where("user='{$_COOKIE['user']}'")->count();

        //兑换积分
        if($_POST['act'] == 'exchange') {
            $a = $user->where("name='{$_COOKIE['user']}'")->setInc('account', $_POST['ex']);
            $b = $user->where("name='{$_COOKIE['user']}'")->setDec('score', $_POST['num']);
            if($a && $b) echo 1;
            exit;
        }

        $this->assign(array(
           'current'=>$current,
           'infocount'=>$infoCount
        ));
        $this->display();
    }

    //头像设置
    public function face() {
        if(isset($_POST['send'])) {
            $face = $this->_post('face');
            $user = M('User');
            $data['face'] = $face;
            if($user->where("name='{$_COOKIE['user']}'")->save($data)) $this->assign('s', 'block');
        }
        $this->display();
    }

    //用户资料设置
    public function userInfo() {
        $user = M('User');
        $info = M('Info');
        $current = $user->field(array('real_name', 'phone', 'qq', 'sex'))
                        ->where("name='{$_COOKIE['user']}'")
                        ->find();

        if(isset($_POST['send'])) {

            $realName = $this->_post('real_name');
            $sex = $this->_post('sex');
            $phone = $this->_post('phone');
            $qq = $this->_post('qq');
            $isAyPhone = $this->_post('is_ay_phone');
            $isAyQQ = $this->_post('is_ay_qq');

            if(!empty($realName)) {
                if(len($realName) < 2 || len($realName) > 5) $this->error('真实姓名长度为2~5位!', 0);
            }
            if(!empty($phone)) {
                if(len($phone) != 11) $this->error('请填写11位手机号码!', 0);
                if(!is_numeric($phone)) $this->error('手机号码必须为数字!', 0);
            }
            if(!empty($qq)) {
                if(len($qq) < 5 || len($qq) > 12) $this->error('qq长度为5~12位!', 0);
                if(!is_numeric($qq)) $this->error('QQ号码必须为数字!', 0);
            }

            //同步更新全部信息的联系电话
            if($isAyPhone == 1) {
                $info->where("user='{$_COOKIE['user']}'")->setField('phone', $phone);
            }
            //同步更新全部信息的qq
            if($isAyQQ == 1) {
                $info->where("user='{$_COOKIE['user']}'")->setField('qq', $qq);
            }

            $data['real_name'] = $realName;
            $data['sex'] = $sex;
            $data['phone'] = $phone;
            $data['qq'] = $qq;
            $user->where("name='{$_COOKIE['user']}'")->save($data);

            $this->assign('s', 'block');
        }

        $this->assign('current', $current);
        $this->display();
    }

    //用户发表过的信息管理
    public function myInfo() {
        $info = M('Info');
        parent::page($info->where("user='{$_COOKIE['user']}'")->count());
        $myInfo = $info->field(array('id', 'title', 'keep', 'addtime', 'stick', 'title'=>'ftitle', 'stick_days', 'stick_time'))
                       ->where("user='{$_COOKIE['user']}'")
                       ->order('addtime DESC')
                       ->limit($this->limit)
                       ->select();


        $oneDay = 3600*24;
        $oneYear = 3600*24*365;
        $oneMonth = 3600*24*30;
        $oneWeek = 3600*24*7;
        foreach($myInfo as $key=>&$value) {
            //处理失效时间
            switch($value['keep']) {
                case '永久有效':
                    $value['keep_tmp'] = '无限';
                    break;
                case '一年':
                    $shut = $oneYear+$value['addtime'];
                    $leave = -floor(time() - $shut);     //向下取整时间
                    $value['keep_tmp'] = floor($leave / $oneDay);
                    break;
                case '一月':
                    $shut = $oneMonth+$value['addtime'];
                    $leave = -floor(time() - $shut);
                    $value['keep_tmp'] = floor($leave / $oneDay);
                    break;
                case '一周':
                    $shut = $oneWeek+$value['addtime'];
                    $leave = -floor(time() - $shut);
                    $value['keep_tmp'] = floor($leave / $oneDay);
                    break;
            }

            //自动删除过期信息
            switch($value['keep']) {
                case '一年':
                    $shut = $oneYear+$value['addtime'];
                    $leave = -floor(time() - $shut);     //向下取整时间
                    if (floor($leave / $oneDay) <= 0) $info->where('id='.$value['id'])->delete();
                    break;
                case '一月':
                    $shut = $oneMonth+$value['addtime'];
                    $leave = -floor(time() - $shut);
                    if (floor($leave / $oneDay) <= 0) $info->where('id='.$value['id'])->delete();
                    break;
                case '一周':
                    $shut = $oneWeek+$value['addtime'];
                    $leave = -floor(time() - $shut);
                    if (floor($leave / $oneDay) <= 0) $info->where('id='.$value['id'])->delete();
                    break;
            }
            //判断置顶是否过期
            if(($value['stick_time'] + $value['stick_days']) - time() < 0) {
                $data['stick'] = 0;
                $data['stick_time'] = '';
                $data['stick_days'] = '';
                $info->where('id='.$value['id'])->save($data);
            }
            //置顶级别说明
            switch($value['stick']) {
                case 0:
                    $value['spell'] = '尚未置顶';
                    break;
                case 1:
                    $value['spell'] = '标题后会有“顶”的图标，在当前小分类中置顶,位置比2级靠后';
                    break;
                case 2:
                    $value['spell'] = '标题后会有“顶”的图标，在当前大分类和小分类中置顶';
                    break;
                case 3:
                    $value['spell'] = '在大小分类中置顶，并且在网站首页中间随机置顶';
                    break;
            }

            //置顶时长
            switch($value['stick_days']) {
                case 86400:
                    $value['stick_days'] = '一天';
                    break;
                case 604800:
                    $value['stick_days'] = '一周';
                    break;
                case 2592000  :
                    $value['stick_days'] = '一月';
                    break;
                default:
                    $value['stick_days'] = '无';
                    break;
            }
        }

        if(isset($_POST['delete'])) {
            $ids = implode(',', $_POST['select']);
            if(!$ids) $this->error('请至少勾选一项删除!', 0);
            $map['id'] = array('in', $ids);
            $info->where($map)->delete() ? $this->assign('s', 'block') : $this->error('系统故障，无法删除信息!', 0);
        }

        //获取当前用户账户金币
        $user = M('User');
        $account = $user->where("name='{$_COOKIE['user']}'")->getField('account');

        $this->assign(array(
            'myinfo'=>$myInfo,
            'account'=>$account
        ));
        $this->display();
    }

    //修改密码
    public function upPass() {
        $user = M('User');
        $condition['name'] = $_COOKIE['user'];
        $ans = $user->where($condition)->getField('ans');
        $ques = $user->where($condition)->getField('ques');
        if(isset($_POST['send'])) {
            $newQues = $this->_post('ques');
            $newAns = $this->_post('ans');
            if($this->_post('newpass') != '') {
                $newPass = $this->_post('newpass');
                $notPass = $this->_post('notpass');
                if(len($newPass) < 6) $this->error('新密码长度至少六位!', 0);
                if($notPass != $newPass) $this->error('两次密码填写不一致!', 0);
                $data['pass'] = sha1($newPass);
            }
            if(empty($newAns)) $this->error('密码问题回答不得为空!', 0);
            $data['ques'] = $newQues;
            $data['ans'] = $newAns;
            $user->where("name='{$_COOKIE['user']}'")->save($data);
            $this->assign('s', 'block');
        }
        $this->assign(array(
            'ques'=>$ques,
            'ans'=>$ans
        ));
        $this->display();
    }

    //用户发布的短信
    public function message() {
        $message = D('Message');

        //发送短信
        if(isset($_POST['send'])) {
            if(cookie('limit')) $this->error('你发短信太频繁了，请喝杯茶再发吧~', 0);
            if($message->create()) {
                if($message->add()) {
                    $this->assign('s', 'block');
                    setcookie('limit', 1, time()+60*3, '/');
                } else {
                    $this->error('系统故障,发送失败!', 0);
                }
            } else {
                $this->error($message->getError(), 0);
            }
        }

        //删除短信
        if(isset($_POST['delete'])) {
            $ids = implode(',', $_POST['select']);
            if(!$ids) $this->error('请至少勾选一项删除!', 0);
            $map['id'] = array('in', $ids);
            $message->where($map)->delete() ? $this->assign('s', 'block') : $this->error('系统故障，无法删除信息!', 0);
        }

        //查看发件箱短信
        if($_GET['type'] == 'view') {
            $view = $message->field(array('id', 'title', 'mfrom', 'mto', 'date', 'content'))
                    ->where('id='.$_GET['id'])
                    ->find();
            //更新阅读
            $message->where("id={$_GET['id']} AND mto='{$_COOKIE['user']}'")->setField('is_read', 1);
        }


        //ajax验证用户名
        if($_POST['ajax'] == 1) {
            $user = M('User');
            $to = $_POST['mto'];
            if(!$user->where("name='$to'")->getField('id')) {
                echo 0;
                exit;
            }
        }

        //查询发件箱
        if($_GET['act'] == 'out') {
            parent::page($message->where("mfrom='{$_COOKIE['user']}'")->count());
            $out = $message->field(array('id', 'title', 'mto', 'date'))
                           ->where("mfrom='{$_COOKIE['user']}'")
                           ->limit($this->limit)
                           ->order('date DESC')
                           ->select();
        }

        //查看收件箱
        if($_GET['act'] == 'in') {
            parent::page($message->where("mto='{$_COOKIE['user']}'")->count());
            $in = $message->field(array('id', 'title', 'mfrom', 'date', 'is_read'))
                      ->where("mto='{$_COOKIE['user']}'")
                      ->order('is_read ASC,date DESC')
                      ->limit($this->limit)
                      ->select();
        }

        $this->assign(array(
            'in'=>$in,
            'out'=>$out,
            'view'=>$view,
            'empty'=>'<tr><td colspan="4">没有任何短信</td></tr>'
        ));

        $this->display();
    }

    //充值
    public function pay() {
        if($_GET['act'] == 'rechargeRecord') {        //充值记录
            $pr = M('payRecord');
            parent::page($pr->where("user='{$_COOKIE['user']}'")->count());
            $payRecord = $pr->field(array('id', 'ordernum', 'pay_ip', 'pay_time', 'pay_num', 'pay_price'))
               ->where("user='{$_COOKIE['user']}'")
               ->order('pay_time DESC')
               ->limit($this->limit)
               ->select();

            //删除充值记录
            if(isset($_POST['delete'])) {
                $ids = implode(',', $_POST['select']);
                if(!$ids) $this->error('请至少勾选一项删除!', 0);
                $map['id'] = array('in', $ids);
                $pr->where($map)->delete() ? $this->assign('s', 'block') : $this->error('系统故障，无法删除记录!', 0);
            }

            $this->assign(array(
               'empty'=>'<tr><td colspan="6">没有任何充值记录</td></tr>',
               'payrecord'=>$payRecord
            ));
        } else {
            //随机生成订单号
            $orderNum = date('YmdHis').rand(10,30).rand(20,40);
            $user = M('User');
            $save = $user->where("name='{$_COOKIE['user']}'")->getField('account');
            $this->assign(array(
                'ordernum'=>$orderNum,
                'save'=>$save
            ));
        }
        $this->display('pay');
    }

    //用户中心
    public function mySpace() {
        $user = M('User');
        $userName = $this->_get('user');
        if(!$user->where("name='$userName'")->getField('id')) $this->error('不存在的用户!');

        //用户基本信息
        $userInfo = $user->field('reg_time, last_time, face')->where("name='$userName'")->find();

        //用户发布过的信息
        $info = M('info');
        parent::page($info->where("user='$userName'")->count(), 30);

        $postInfo = $info->alias('xi')
                         ->field(array('xi.id', 'xi.title', 'xi.addtime', 'xn.name'))
                         ->join('xinxi_info_nav as xn ON xi.cid=xn.id')
                         ->where("xi.user='$userName'")
                         ->order('addtime DESC')
                         ->limit($this->limit)
                         ->select();

        $this->assign(array(
           'userinfo'=>$userInfo,
           'postinfo'=>$postInfo
        ));
        $this->display();
    }

    //退出
    public function logout() {
        if(setcookie('user', '', time()-10, '/')) jump(__ROOT__.'/User/login');
    }

}